package com.alander.nexusgo.im.netty;

import cn.hutool.json.JSONUtil;
import com.alander.nexusgo.im.constants.ImConstants;
import com.alander.nexusgo.im.constants.ImMsgCodeEnum;
import com.alander.nexusgo.im.model.dto.ImMsg;
import com.alander.nexusgo.im.model.dto.ImMsgBody;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 单聊消息处理器
 */
public class PrivateChatHandler extends SimpleChannelInboundHandler<ImMsg> {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(PrivateChatHandler.class);
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ImMsg msg) throws Exception {
        // 只处理业务消息
        if (msg.getCode() == ImMsgCodeEnum.IM_BIZ_MSG.getCode()) {
            handlePrivateMessage(msg);
        } else {
            // 将消息传递给下一个处理器
            ctx.fireChannelRead(msg);
        }
    }
    
    /**
     * 处理单聊消息
     * @param msg 消息
     */
    private void handlePrivateMessage(ImMsg msg) {
        try {
            // 解析消息体
            String bodyJson = new String(msg.getBody());
            ImMsgBody msgBody = JSONUtil.toBean(bodyJson, ImMsgBody.class);
            
            // 获取目标用户的通道
            Long targetUserId = (long) msgBody.getBizCode(); // 使用bizCode作为目标用户ID
            Long senderUserId = msgBody.getUserId(); // 发送者用户ID
            
            // 检查发送者和接收者不能是同一人
            if (targetUserId.equals(senderUserId)) {
                LOGGER.warn("发送者和接收者不能是同一人: userId={}", senderUserId);
                return;
            }
            
            // 查找目标用户的通道
            io.netty.channel.Channel targetChannel = ImConnectionManager.getUserChannel(targetUserId);
            if (targetChannel == null || !targetChannel.isActive()) {
                LOGGER.warn("目标用户不在线: userId={}", targetUserId);
                return;
            }
            
            // 构造返回消息
            ImMsg response = new ImMsg();
            response.setMagic(ImConstants.DEFAULT_MAGIC);
            response.setCode(ImMsgCodeEnum.IM_BIZ_MSG.getCode());
            
            // 重新构造消息体，确保只传输必要信息
            ImMsgBody responseBody = new ImMsgBody();
            responseBody.setAppId(msgBody.getAppId());
            responseBody.setUserId(senderUserId); // 设置发送者ID
            responseBody.setBizCode(Math.toIntExact(senderUserId)); // 设置发送者ID为bizCode
            responseBody.setMsgId(msgBody.getMsgId());
            responseBody.setData(msgBody.getData());
            
            String responseBodyJson = JSONUtil.toJsonStr(responseBody);
            byte[] responseBodyBytes = responseBodyJson.getBytes();
            
            response.setLen(responseBodyBytes.length);
            response.setBody(responseBodyBytes);
            
            // 发送给目标用户
            targetChannel.writeAndFlush(response);
            
            LOGGER.info("单聊消息发送成功: from={} to={} msgId={}", senderUserId, targetUserId, msgBody.getMsgId());
        } catch (Exception e) {
            LOGGER.error("处理单聊消息时发生错误", e);
        }
    }
}